package com.ruoyi.system.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author mrc
 * RedisToken工具类
 */
@Component
public class RedisToken {


    @Autowired
    private RedisService redisService;
    /**
     *     token名称
     */
    public static final String TOKEN_NAME = "access_token";

    /**
     * 更新token最低时间(分钟)
     */
    private static final Integer EXPIRE_TIME = 120;

    private static final String IP = "ip";

    /**
     * 更新token最低时间(分钟)
     */
    private static final Integer RENEW_TIME_LIMIT = 30;

    /**
     * 续期token的时间(分钟)
     */
    private static final Integer RENEW_TIME = 60;

    /**
     * 生成token
     * @param ip
     * @return
     */
    public String createToken(String ip) {
        JSONObject object = new JSONObject();
        object.put(IP, ip);
        String token = IdUtil.fastSimpleUUID();
        redisService.setCacheObject(token, object.toJSONString(), EXPIRE_TIME, TimeUnit.MINUTES);
        return token;
    }

    private boolean isTokenWillExpired(String token) {
        return redisService.getExpire(token,TimeUnit.MINUTES).intValue() < RENEW_TIME_LIMIT;
    }

    public boolean isTokenExpired(String token) {
        boolean b = true;
        if (redisService.hasKey(token)) {
            b = false;
            if (isTokenWillExpired(token)){
               // 续期
                redisService.expire(token,redisService.getExpire(token,TimeUnit.MINUTES).intValue()+ RENEW_TIME,TimeUnit.MINUTES);
            }
        }
        return b;
    }


    public void logOut(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        redisService.deleteObject(token);
    }

    private JSONObject getSomeThingFormToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        String val = redisService.getCacheObject(token);
        return (JSONObject) JSONObject.parse(val);
    }

    public String getIpFromToken(HttpServletRequest request) {
        return getSomeThingFormToken(request).get(IP).toString();
    }
}
